package com.example.electronicmall.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.electronicmall.R;
import com.example.electronicmall.adapter.ShoppingCartAdapter;
import com.example.electronicmall.application.BaseApplication;
import com.example.electronicmall.base.DocxActivity;
import com.example.electronicmall.bean.ShoppingCartBean;
import com.example.electronicmall.bean.ShoppingHttpBeanInside;
import com.example.electronicmall.bean.ShoppingHttpBeanoutside;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ShoppingCartFragment extends Fragment implements ShoppingCartAdapter.ModifyCountInterface, ShoppingCartAdapter.CheckInterface {
    private ShoppingCartBean bean;
    private CheckBox allCheckBox;
    private TextView heji;
    private List<ShoppingCartBean> beanList;
    private ShoppingCartAdapter adapter;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    private ListView listView;
    private TextView enment;


    private String TAG = ShoppingCartFragment.class.getCanonicalName();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shopping_cart, container, false);
    }

    private <T extends View> T findViewById(@IdRes int resid) {
        return getView().findViewById(resid);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initview();


    }

    Handler handler = new Handler();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            initviews();
            setinterface();
            listView.setAdapter(adapter);
        }
    };


    private void initview() {
        listView = findViewById(R.id.shapping_listview);
        enment = findViewById(R.id.shopping_cart_settenment);
        allCheckBox = findViewById(R.id.shopping_all_checkbox);
        heji = findViewById(R.id.shopping_heji);
        beanList = new ArrayList<>();

        BaseApplication.request.requestshoppingCart()
                .enqueue(new Callback<ShoppingHttpBeanoutside<ShoppingHttpBeanInside>>() {
                    @Override
                    public void onResponse(Call<ShoppingHttpBeanoutside<ShoppingHttpBeanInside>> call, Response<ShoppingHttpBeanoutside<ShoppingHttpBeanInside>> response) {
                        ShoppingHttpBeanInside[] beanInside = response.body().getData();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                for (int j = 0; j < beanInside.length; j++) {
                                    bean = new ShoppingCartBean();
                                    bean.setShopsname(beanInside[j].getProductSubTitle());
                                    bean.setShopsmoney(String.valueOf(beanInside[j].getPrice()));
                                    bean.setShopscoupon(beanInside[j].getProductAttr());
                                    bean.setShopstitle(beanInside[j].getProductName());
                                    bean.setShopsnumber("1");
                                    beanList.add(bean);
                                    beanInside[j].getProductPic();
                                    Log.d(TAG, "图片" + beanInside[j].getProductPic() + "");
                                    Log.i(TAG, "number:" + beanInside[j].getProductSn() + "-money:" + String.valueOf(beanInside[j].getPrice()) + "数量：" + beanInside.length);
                                    try {
                                        Bitmap bitmap;
                                        URL uri = new URL(beanInside[j].getProductPic());
                                        HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
                                        connection.setReadTimeout(5000);
                                        connection.setConnectTimeout(5000);
                                        connection.connect();

                                        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                            InputStream inputStream = connection.getInputStream();
                                            bitmap = BitmapFactory.decodeStream(inputStream);
                                            Log.d(TAG, "转化图片" + bitmap);
                                            bean.setShopsicon(bitmap);
                                        }
                                        adapter = new ShoppingCartAdapter(getActivity(), beanList);

                                        handler.post(r);

                                    } catch (MalformedURLException e) {
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }

                            }
                        }).start();
                        Log.d(TAG, "几条数据" + beanInside.length);

                    }

                    @Override
                    public void onFailure(Call<ShoppingHttpBeanoutside<ShoppingHttpBeanInside>> call, Throwable t) {
                        t.fillInStackTrace();
                        Log.d(TAG, "异常错误" + t);
                    }
                });
        //删除购物车
        TextView shoppingmore = findViewById(R.id.shopping_more);
        shoppingmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shoppingmore.getText().equals("管理")) {
                    shoppingmore.setText("退出管理");
                    shoppingmore.setTextColor(Color.parseColor("#E00A0A"));

                    enment.setText("删除");
                    enment.setTextColor(Color.parseColor("#E00A0A"));

                } else if (shoppingmore.getText().equals("退出管理")) {
                    shoppingmore.setTextColor(Color.BLACK);
                    shoppingmore.setText("管理");
                    enment.setTextColor(Color.WHITE);
                    enment.setText("结算");
                }
            }

        });
        enment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (enment.getText().equals("结算")) {
                    startActivity(new Intent(getContext(), DocxActivity.class));
                } else if (enment.getText().equals("删除")) {
                    delect();
                }
            }

        });
//        listView.setAdapter(adapter);
    }

    //删除的业务逻辑
    private void delect(){
        for (int i= beanList.size()-1;i>=0;i--) {
            Log.i(TAG, "checkbox:" + allCheckBox.isChecked());
            if(beanList.get(i).isChoosed()){
                beanList.remove(i);
            }
        }
        adapter.notifyDataSetChanged();
        calculate();
    }

    private void initviews() {
        allCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                allcheckbox();
            }
        });

    }

    private void setinterface() {
        adapter.setCheckInterface(this);// 关键步骤1,设置复选框接口
        adapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
    }

    //全选与反选
    private void allcheckbox() {
        Log.i(TAG, "checkbox-size:" + beanList.size());
        for (ShoppingCartBean info : beanList) {
            Log.i(TAG, "checkbox:" + allCheckBox.isChecked());
            info.setChoosed(allCheckBox.isChecked());
        }
        adapter.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        heji = null;
        allCheckBox = null;
    }

    private boolean isAllCheck() {
        for (ShoppingCartBean info : beanList) {
            if (!info.isChoosed())
                return false;
        }
        return true;
    }

    //价格判断
    private void calculate() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int j = 0; j < beanList.size(); j++) {
            ShoppingCartBean product = beanList.get(j);
            if (product.isChoosed()) {
                //TODO 问题：product.getShopsnumber()这个参数返回为空
                String number = product.getShopsnumber() != null ? product.getShopsnumber() : "0";
                String money = product.getShopsmoney() != null ? product.getShopsmoney() : "0";
                totalCount += Integer.parseInt(number);
                totalPrice += Double.parseDouble(money) * Double.parseDouble(number);
            }
        }
        heji.setText("¥" + totalPrice);
    }

    @Override
    public void checkChild(int childPosition, boolean isChecked) {
        if (isAllCheck()) {
            allCheckBox.setChecked(true);
        } else {
            allCheckBox.setChecked(false);
        }
        ShoppingCartBean info = (ShoppingCartBean) adapter.getItem(childPosition);
        info.setChoosed(isChecked);
        adapter.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void doIncrease(int childPosition, View showCountView, boolean isChecked) {
        ShoppingCartBean info = (ShoppingCartBean) adapter.getItem(childPosition);
        int currentCount = Integer.parseInt(info.getShopsnumber());
        currentCount++;
        info.setShopsnumber(String.valueOf(currentCount));
        ((TextView) showCountView).setText(currentCount + "");

        adapter.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void doDecrease(int childPosition, View showCountView, boolean isChecked) {
        ShoppingCartBean info = (ShoppingCartBean) adapter.getItem(childPosition);
        int currentCount = Integer.parseInt(info.getShopsnumber());
        if (currentCount == 1)
            return;
        currentCount--;

        info.setShopsnumber(String.valueOf(currentCount));
        ((TextView) showCountView).setText(currentCount + "");
        adapter.notifyDataSetChanged();
        calculate();
    }
}